<template>
  <NuxtLayout>
    <el-breadcrumb class="my-crumb">
      <el-breadcrumb-item v-for="(item, index) in crumbData" :key="index">
        <a :href="item.href">{{ item.title }}</a>
      </el-breadcrumb-item>
    </el-breadcrumb>
    <div class="con">
      <div class="con_cen">
        <div class="con_cen_left">
          <div class="con_cen_left_title">{{ leftTitle }}</div>
          <div class="con_cen_left_notice">
            <el-icon size="20" color="#DADADA">
              <InfoFilled />
            </el-icon>
            <span class="con_cen_left_notice_text">回答问题自动显示解析</span>
          </div>
          <div class="con_cen_left_page">
            <div class="con_cen_left_page_notdone" v-if="way == 'notDone'">共计<strong class="success">{{ total
                }}</strong>道题未做</div>
            <ul class="con_cen_left_page_list" v-else>
              <template v-for="(item, index) in numListData" :key="item.id">
                <li class="con_cen_left_page_list_num" :class="item.correct ? 'success' : 'error'" @click="pageJumpFn(item, index + 1)" v-if="p != index + 1 && item.answer">{{ index + 1 }}</li>
                <li class="con_cen_left_page_list_num" :class="item.correct ? 'success' : 'error'" v-else-if="p == index + 1 && item.answer">{{ index + 1 }}</li>
                <li class="con_cen_left_page_list_num active" v-else-if="p == index + 1">{{ index + 1 }}</li>
                <li class="con_cen_left_page_list_num" @click="pageJumpFn(item, index + 1)" v-else>{{ index + 1 }}</li>
              </template>
            </ul>
            <div class="con_cen_left_page_mask"></div>
          </div>
        </div>
        <div class="con_cen_right">
          <div class="con_cen_right_label" v-show="typeName">
            <div class="con_cen_right_label_type" v-show="typeName">{{ typeName }}</div>
          </div>
          <div class="con_cen_right_item">
            <div class="con_cen_right_item_title" v-show="listData.question">{{ listData.question }}</div>
            <template v-if="listData.imgs && listData.imgs.length > 0">
              <div class="con_cen_right_item_cover" v-for="(item, index) in listData.imgs" :key="index">
                <el-image class="con_cen_right_item_cover_image" :src="item" :preview-src-list="listData.imgs" :initial-index="index" v-show="(index + 1) >= listData.imgs.length" />
              </div>
            </template>
            <video class="con_cen_right_item_video" :src="listData.video" controls v-show="listData.video"></video>
            <!-- 未答题 -->
            <ul class="con_cen_right_options" v-if="!listData.answer">
              <li class="con_cen_right_options_item" v-for="item in listData.options" :key="item.letter" @click="chooseFn(item)">
                <el-icon class="con_cen_right_options_item_icon" size="20" color="#00C745"
                  v-if="item.checked">
                  <CircleCheck />
                </el-icon>
                <em class="con_cen_right_options_item_icon round" v-else></em>
                <span class="con_cen_right_options_item_letter">{{ item.letter }}，</span>
                <div class="con_cen_right_options_item_title" v-html="item.title"></div>
                <el-image class="con_cen_right_options_item_img" :src="item.imgUrl" :preview-src-list="[item.imgUrl]" fit="cover" v-if="item.imgUrl" />
              </li>
            </ul>
            <!-- 已答题 -->
            <ul class="con_cen_right_options" v-else>
              <li class="con_cen_right_options_item" v-for="item in listData.options" :key="item.letter">
                <el-icon class="con_cen_right_options_item_icon selected" size="20" color="#00C745"
                  v-if="listData.answer.includes(item.letter) && listData.correctAnswer.includes(item.letter)">
                  <CircleCheckFilled />
                </el-icon>
                <el-icon class="con_cen_right_options_item_icon selected" size="20" color="#FF3F29"
                  v-else-if="listData.answer.includes(item.letter) && !listData.correctAnswer.includes(item.letter)">
                  <CircleCloseFilled />
                </el-icon>
                <em class="con_cen_right_options_item_icon round selected" v-else></em>
                <span class="con_cen_right_options_item_letter">{{ item.letter }}，</span>
                <div class="con_cen_right_options_item_title" v-html="item.title"></div>
                <el-image class="con_cen_right_options_item_img" :src="item.imgUrl" :preview-src-list="[item.imgUrl]" fit="cover" v-if="item.imgUrl" />
              </li>
            </ul>
            <div class="con_cen_right_page">
              <el-button round @click="pageChangeFn('prev')"
                v-if="p > 1">&nbsp;&nbsp;上一题&nbsp;&nbsp;</el-button>
              <el-button round @click="pageChangeFn('next')"
                v-if="p < total">&nbsp;&nbsp;下一题&nbsp;&nbsp;</el-button>
              <el-button type="primary" round :disabled="checkDisabled" @click="checkChangeFn"
                v-if="listData.type == 1 && !listData.answer">&nbsp;&nbsp;多选确认&nbsp;&nbsp;</el-button>
            </div>
            <template v-if="listData.answer">
              <div class="con_cen_right_answer">
                <strong class="con_cen_right_answer_tips success"
                  v-if="listData.answer == listData.correctAnswer">回答正确</strong>
                <strong class="con_cen_right_answer_tips error" v-else>回答错误</strong>
                <div class="con_cen_right_answer_rightkey">正确答案：<strong class="success">{{ listData.correctAnswer ||
                    ''}}</strong></div>
              </div>
              <div class="con_cen_right_analysis">
                <div class="con_cen_right_analysis_tips">试题解析</div>
                <div class="con_cen_right_analysis_con">{{ listData.analysis || '暂无试题解析...' }}</div>
              </div>
            </template>
          </div>
        </div>
      </div>
    </div>
  </NuxtLayout>
</template>

<script setup>
import { useCountStore } from '~/store/counter'
import { userExerciseRecordList, getExercise, getExercisesListApi, addExerciseRecordApi } from '~/server/api'
import { InfoFilled, CircleCheckFilled, CircleCloseFilled, CircleCheck } from '@element-plus/icons-vue'
useCountStore().$patch({ indexActive: 4 })
const crumbData = ref([])
definePageMeta({
  validate: async (route) => {
    return /^1\d{5,}$/.test(route.params.id) && route.params.type && (route.params.type == 'all' || route.params.type == 'selected' || route.params.type == 'wrong');
  }
})
const prevHost = useRequestHeaders()["x-forwarded-proto"];
const host = useRequestHeaders()["host"];
const fullPath = useRoute()["fullPath"];
const title = ref('题库中心');
const keywords = ref('题库中心');
const description = ref('题库中心');
const subjectId = useRoute().params.id || '';
const way = useRoute().params.type || '';
const numListForm = reactive({
  exerciseOpen: true,
  subjectId,
  selected: way == 'selected' ? true : '',
  done: way == 'notDone' ? false : '',
  correct: way == 'wrong' ? false : ''
})
const numListData = ref([])
const p = ref(1)
const recordForm = reactive({
  exerciseId: null,
  answer: ''
})
const total = ref(0);
const pages = ref(0);
const listData = ref({});
const leftTitle = ref(way == 'selected' ? '精选练题' : way == 'notDone' ? '未做习题' : way == 'wrong' ? '我的错题' : '全部习题');
const typeName = ref(null);
const checkDisabled = ref(false);
// 获取答题卡
async function getNumList() {
  let res = await useServerRequest(userExerciseRecordList, {
    method: 'post',
    body: JSON.stringify(numListForm)
  })
  if (res && res.errno === 0 && res.result.length > 0) {
    numListData.value = res.result;
    total.value = res.result.length;
    getInfo(res.result[p.value > 0 ? p.value - 1 : 0].exerciseId)
    return false;
  }
  showError({ statusCode: 404, statusMessage: `Page not found: ${useRoute().path}` });
}
// 获取习题详情
async function getInfo(exerciseId) {
  let res = await useServerRequest(getExercise, {
    method: 'get',
    params: { exerciseId }
  })
  if (res && res.errno === 0 && res.result) {
    res.result.options.filter(x => x.checked = false); // 设置选项主题默认值
    res.result = {...res.result, ...numListData.value[p.value ? p.value - 1 : 0]}; // 追加字段
    listData.value = res.result;
    crumbData.value = [
      { title: '首页', href: '/' },
      { title: '题库中心', href: '/exercises' },
      { title: listData.value.subjectName, href: 'javascript:;' }
    ]
    typeName.value = res.result.type === 0 ? '单选题' : res.result.type === 1 ? '多选题' : '判断题';
    recordForm.exerciseId = res.result.id; // 记录习题ID
    // TDK
    title.value = `${listData.value.question}`;
    keywords.value = `${listData.value.question}`;
    description.value = `${leftTitle.value}，${typeName.value}，${listData.value.question}`;
    return false
  }
  showError({ statusCode: 404, statusMessage: `Page not found: ${useRoute().path}` });
}
// 上一题 下一题
function pageChangeFn(type) {
  // 上一题
  if (type === 'prev') {
    if (p.value < 2) {
      ElMessage.warning('已是第一题')
      return false;
    }    
    listData.value = {};
    getInfo(numListData.value[p.value - 2].exerciseId)
    localStorage.setItem('p', p.value - 1)
    p.value -= 1;
  }
  // 下一题
  if (type === 'next') {
    if (p.value >= total.value) {
      ElMessage.warning('已是最后一题')
      return false;
    }
    listData.value = {};
    getInfo(numListData.value[p.value].exerciseId)
    localStorage.setItem('p', p.value + 1)
    p.value += 1;
  }
}
// 分页跳转
function pageJumpFn(val, ind) {
  localStorage.setItem('p', ind)
  p.value = ind;
  listData.value = {};
  getInfo(val.exerciseId)
}
// 选择
function chooseFn(val) {
  if (listData.value.type == 0 || listData.value.type == 2) { // 单选 判断
    recordForm.answer = val.letter;
    saveRecord()
  } else { // 多选
    val.checked = !val.checked;
  }
}
// 多选确认
function checkChangeFn() {
  let answerFilter = listData.value.options && listData.value.options.length > 0 ? listData.value.options.filter(x => x.checked) : [];
  let answerMap = answerFilter.map(x => x.letter);
  recordForm.answer = answerMap.join('');
  if (recordForm.answer == '') {
    ElMessage.warning('请选择答案')
    return false
  }
  saveRecord()
}
// 记录
async function saveRecord() {
  if (listData.value.type == 1) {
    checkDisabled.value = true;
  }
  let res = await useServerRequest(addExerciseRecordApi, {
    method: 'post',
    body: JSON.stringify(recordForm)
  })
  if (res && res.errno === 0) {
    getNumList()
  }
  if (listData.value.type == 1) {
    checkDisabled.value = false;
  }
}
// TDK
useSeoMeta({
  title,
  keywords,
  description,
  ogTitle: title,
  ogDescription: description,
  ogType: "article",
  ogUrl: `${prevHost}://${host}${fullPath}`,
})
// 回退
const handlePopState = (event) => {
  // 清除缓存
  if (localStorage.getItem('p')) {
    localStorage.removeItem('p')
    window.history.back()
  }
}
// 挂载后
onMounted(() => {
  // 读取缓存分页
  if (localStorage.getItem('p')) {
    p.value = parseInt(localStorage.getItem('p'));
  }
  getNumList()
  // 浏览器事件
  window.history.pushState(null, null, '')
  window.addEventListener('popstate', handlePopState);
})
// 卸载后
onUnmounted(() => {
  window.removeEventListener('popstate', handlePopState);
})
</script>

<style lang="less" scoped>
* {
  user-select: none;
}

.con {
  min-height: calc(100vh - 454px);
  box-sizing: border-box;
  padding: 20px 0;

  &_cen {
    width: 1200px;
    margin: 0 auto;
    display: flex;
    align-items: flex-start;

    &_left {
      width: 300px;
      height: 459px;
      background: #fff url('https://static.dzyxzx.cn/jkbpc/practice_card_back.png') top left / 100% no-repeat;
      border-radius: 10px;
      box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.03);
      margin-right: 20px;
      overflow: hidden;

      &_title {
        font-weight: bold;
        font-size: 24px;
        text-align: center;
        padding-top: 70px;
        line-height: 36px;
      }

      &_notice {
        margin-top: 92px;
        display: flex;
        align-items: center;
        justify-content: center;

        &_text {
          font-size: 14px;
          color: #666666;
          margin-left: 7px;
          line-height: 20px;
        }
      }

      &_page {
        height: calc(100% - 243px);
        margin-top: 25px;
        position: relative;

        &_list {
          height: 100%;
          overflow-y: auto;
          padding-right: 15px;
          padding-bottom: 15px;
          padding-left: 10px;

          &_num {
            width: 35px;
            height: 35px;
            line-height: 33px;
            border-radius: 35px;
            text-align: center;
            overflow: hidden;
            font-size: 13px;
            box-sizing: border-box;
            border: 1px solid #ccc;
            color: #ccc;
            cursor: pointer;
            margin: 0 0 15px 15px;
            float: left;

            &:hover,
            &.active {
              border-color: #409eff;
              color: #409eff;
            }

            &.success {
              border-color: #00C745;
              background-color: #00C745;
              color: #fff;
              
            }

            &.error {
              border-color: #FF3F29;
              background-color: #FF3F29;
              color: #fff;
            }
          }
        }

        &_notdone {
          font-size: 18px;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;

          .success {
            color: #00C745;
          }
        }

        &_mask {
          position: absolute;
          right: 17px;
          bottom: 0;
          left: 0;
          z-index: 1;
          height: 30px;
          background: linear-gradient(transparent, #fff);
        }
      }
    }

    &_right {
      flex: 1;
      min-height: 459px;
      background-color: #fff;
      border-radius: 10px;
      box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.03);
      padding: 30px;
      box-sizing: border-box;
      display: flex;
      align-content: start;

      &_label {
        white-space: nowrap;

        &_type {
          margin: 9px 12px 0 0;
          height: 20px;
          line-height: 20px;
          padding: 0 5px;
          border-radius: 5px;
          background-color: #E3F0FF;
          color: #64A0E6;
          font-size: 14px;
        }
      }

      &_item {
        flex: 1;

        &_title {
          line-height: 36px;
          font-size: 18px;
          display: flex;
          flex-wrap: wrap;
          margin-bottom: 12px;
        }

        &_cover {
          margin-bottom: 12px;
          overflow: hidden;

          &_image {
            max-width: 100%;
            float: left;
            cursor: pointer;
          }
        }

        &_video {
          max-width: 100%;
          height: 300px;
          display: block;
          background-color: #000;
          margin-bottom: 12px;
        }
      }

      &_options {
        // margin-top: 12px;
        // padding-left: 64px;

        &_item {
          display: flex;
          align-content: flex-start;

          &_icon {
            margin: 9px 14px 0 0;
            cursor: pointer;

            &.round {
              width: 20px;
              height: 20px;
              display: flex;
              align-items: center;
              justify-content: center;

              &::after {
                content: '';
                border: 1px solid #ccc;
                width: 17.5px;
                height: 17.5px;
                border-radius: 50%;
                box-sizing: border-box;
                display: block;
              }
            }

            &.selected {
              cursor: auto;
            }
          }

          &_letter {
            line-height: 36px;
            font-size: 18px;
          }

          &_title {
            line-height: 36px;
            font-size: 18px;
            display: flex;
            flex-wrap: wrap;
          }

          &_img {
            // width: 100px;
            height: 36px;
            margin-left: 10px;
          }
        }
      }

      &_page {
        margin-top: 20px;
        // padding-left: 64px;
      }

      &_answer {
        // padding-left: 64px;
        margin-top: 44px;
        display: flex;
        align-items: baseline;

        &_tips {
          font-size: 18px;
          margin-right: 20px;

          &.success {
            color: #00C745;
          }

          &.error {
            color: #FF3F29;
          }
        }

        &_rightkey {
          font-size: 14px;

          >strong {
            font-size: 18px;
            color: #666;

            &.success {
              color: #00C745;
            }

            &.error {
              color: #FF3F29;
            }
          }
        }
      }

      &_analysis {
        margin-top: 70px;

        &_tips {
          font-weight: bold;
          font-size: 18px;
        }

        &_con {
          margin-top: 15px;
          line-height: 24px;
          color: #666;
          font-size: 14px;
        }
      }
    }
  }
}
</style>